package com.franklin.validation.core.argument.impl.string;

import com.franklin.validation.core.annotations.ParamCheck;
import com.franklin.validation.core.argument.impl.AbstractResolverResult;
import com.franklin.validation.core.entity.CheckFormEntity;
import com.franklin.validation.core.entity.CheckResult;
import com.franklin.validation.core.utils.DataCheckUtil;
import com.franklin.validation.core.utils.ReflectionUtil;

import java.util.List;
import java.util.regex.Pattern;

/**
 * Description : 字符串结果处理器
 * Create By: Franklin
 * Date : 2020/6/15 14:36
 */
public abstract class AbstractStringResolverResult<R> extends AbstractResolverResult<R> {

    protected boolean checkPattern(String value,String pattern){
        if (DataCheckUtil.isEmpty(pattern)){
            return true;
        }
        return Pattern.compile(pattern).matcher(value).matches();
    }

    @Override
    public CheckResult check(CheckFormEntity input) {
        ParamCheck paramCheck = input.getParamCheck();
        String value = this.getStringValue(input.getValues());
        CheckResult<String> result = new CheckResult<>();
        result.setSuccess(false);
        result.setParam(paramCheck.value());
        boolean lengthPass = this.checkSize(input);
        boolean patternPass = this.checkPattern(value,paramCheck.pattern());
        boolean isEmpty = DataCheckUtil.isEmpty(value);
        if (paramCheck.required()){
            //必填
            if (isEmpty){
                result.setMessage(this.getErrorMessage(paramCheck));
            }else if (!patternPass || !lengthPass){
                result.setMessage(this.getErrorMessage(paramCheck));
            }else {
                result.setSuccess(true);
            }
        }else {
            //非必填
            if (!patternPass || !lengthPass){
                result.setMessage(this.getErrorMessage(paramCheck));
            }else {
                result.setSuccess(true);
            }
        }
        return result;
    }

    @Override
    public boolean checkSize(CheckFormEntity input) {
        ParamCheck paramCheck = input.getParamCheck();
        String value = this.getStringValue(input.getValues());
        return paramCheck.max() >= value.length() && paramCheck.min() <= value.length();
    }

    /**
     * 读取参数
     * @param values
     * @return
     */
    protected String getStringValue(List<String> values){
        return DataCheckUtil.isEmpty(values) ? "" : DataCheckUtil.trim(values.get(0));
    }

}
